#include "AnonObjFile.h"
#include "COFFFile.h"
#include <iostream>
#include <stdio.h>

CAnonObjFile::CAnonObjFile()
	: pAnonHeader_(NULL)
{
}


CAnonObjFile::~CAnonObjFile()
{
}

BOOL CAnonObjFile::Init(PBYTE  pBase, DWORD dwSize)
{
	if (FALSE == CFileBase::Init(pBase, dwSize))
	{
		return FALSE;
	}

	pAnonHeader_ = (ANON_OBJECT_HEADER*)pBase_;
	return TRUE;
}

BOOL CAnonObjFile::UnInit()
{
	pAnonHeader_ = NULL;
	return TRUE;
}

void CAnonObjFile::PrintFileInfo(const char* szPrefix /*= ""*/)
{
	std::cout << szPrefix << "ANON-COFF File Type" << std::endl;
	switch (pAnonHeader_->Machine)
	{
	case IMAGE_FILE_MACHINE_I386:
		std::cout << szPrefix << "Machine:I386;" << std::endl;
		break;
	case IMAGE_FILE_MACHINE_IA64:
		std::cout << szPrefix << "Machine:IA64;" << std::endl;
		break;
	case IMAGE_FILE_MACHINE_AMD64:
		std::cout << szPrefix << "Machine:AMD64;" << std::endl;
		break;
	default:
		break;
	}

	printf("%sTimeDateStamp:%08X\n", szPrefix, pAnonHeader_->TimeDateStamp);

	if (pAnonHeader_->Version >= 2)
	{
		ANON_OBJECT_HEADER_BIGOBJ* pBigObjHeader = (ANON_OBJECT_HEADER_BIGOBJ*)pAnonHeader_;
		printf("%sNumberOfSections:%u\n", szPrefix, pBigObjHeader->NumberOfSections);
		printf("%sNumberOfSymbols:%u\n", szPrefix, pBigObjHeader->NumberOfSymbols);
	}
	
	if (pAnonHeader_->Version >= 1)
	{
		printf("%sSizeOfData:%08X\n", szPrefix, pAnonHeader_->SizeOfData);
	}

	DWORD dwOffset = sizeof(ANON_OBJECT_HEADER);

	if (pAnonHeader_->Version >= 2)
	{
		dwOffset = sizeof(ANON_OBJECT_HEADER_BIGOBJ);
	}
	else if (pAnonHeader_->Version == 0)
	{
		dwOffset = 12;
	}

	FILE_TYPE ftype = GuessFileType(pBase_ + dwOffset);
	if (ftype == FILE_TYPE::COFF)
	{
		COFFFile coff;
		coff.Init(pBase_ + dwOffset, dwSize_ = dwOffset);
		coff.PrintFileInfo(szPrefix);
	}
	else if (ftype == FILE_TYPE::Unknown)
	{
		PrintRawData(pBase_, dwSize_);
	}
}
